package Offer2019;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class CallableDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //两个线程，一个main主线程，一个是AA-futureTask线程

        //public FutureTask(Callable<V> callable)
        //创建一个 FutureTask ，它将在运行时执行给定的 Callable 。
        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());
        FutureTask<Integer> futureTask2 = new FutureTask<>(new MyThread());

        new Thread(futureTask,"AA").start();
        new Thread(futureTask2,"BB").start();

        //建议放在后面写
        Integer result = futureTask.get();//要求获得Callable线程的计算结果，如果没有计算完成就要去强求，会导致堵塞，直到计算完成
        System.out.println(Thread.currentThread().getName());

        System.out.println("result:"+result);

        String s = "123";
        char[] chars = s.toCharArray();
    }
}

class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+"\tCome in Callable");
        TimeUnit.SECONDS.sleep(3);
        return 1024;
    }
}
